package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.OrganizaPageReq;
import appapi.dao.CompanyMapper;
import appapi.dao.OrganizationMapper;
import appapi.dao.ProjectMapper;
import appapi.dao.StaffMapper;
import appapi.entity.Zhongjiao.CompanyDto;
import appapi.entity.Zhongjiao.OrganizationDto;
import appapi.entity.Zhongjiao.ProjectDto;
import appapi.entity.Zhongjiao.StaffDto;
import appapi.entity.basic.UserInfo;
import appapi.service.IOrganization;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author djq
 * @date 2023/5/23 10:56
 * @description:
 */
@Component
public class OrganizationImpl implements IOrganization {
    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    StaffMapper staffMapper;

    @Override
    public List<Map<String, Object>> SelectOrganizationPage(OrganizaPageReq dto) {

        PageHelper.startPage(dto.getCurrPage(), dto.getPageSize());

        List<Map<String, Object>> dataList = organizationMapper.selectOrgList(dto);

        return dataList;
    }

    @Override
    public Map<String, Object> SelectOrgDetail(Long orgaId) {
        return organizationMapper.selectOrgDetail(orgaId);
    }

    @Override
    public OrganizationDto detail(Long orgaId) {
        return organizationMapper.selectByPrimaryKey(orgaId);
    }

    @Override
    public void InsertOrganization(OrganizationDto dto) {
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        int iRet =organizationMapper.insertSelective(dto);
        if(iRet>0)
        {
            //获取父级对象
            OrganizationDto parent=organizationMapper.selectByPrimaryKey(Long.parseLong(dto.getOrgaPid().toString()));
            Long orgaId=dto.getOrgaId();
            dto.setOrgaPathIds(parent.getOrgaPathIds().concat("-").concat(orgaId.toString()));
            dto.setOrgaPathName(parent.getOrgaPathName().concat("-").concat(dto.getOrgaName()));
            organizationMapper.updateByPrimaryKey(dto);
        }
       if (iRet==0)
           throw new BusinessException(500,"新增失败");
    }

    @Override
    public void UpdateOrganization(OrganizationDto dto) {
        dto.setUpdateTime(LocalDateTime.now());
        if (dto.getOrgaId()==null)
            throw new BusinessException(500,"id不能为空!");
        int iRet=organizationMapper.updateByPrimaryKeySelective(dto);
        if(iRet>0)
        {
            //获取父级对象
            OrganizationDto parent=organizationMapper.selectByPrimaryKey(Long.parseLong(dto.getOrgaPid().toString()));
            Long orgaId=dto.getOrgaId();
            dto.setOrgaPathIds(parent.getOrgaPathIds().concat("-").concat(orgaId.toString()));
            dto.setOrgaPathName(parent.getOrgaPathName().concat("-").concat(dto.getOrgaName()));
            organizationMapper.updateByPrimaryKey(dto);
        }
        if (iRet==0)
            throw new BusinessException(500,"编辑失败");
    }

    @Override
    public void DelOrganization(Long orgaId) {
        if (orgaId==null)
            throw new BusinessException(500,"id不能为空!");
        if (organizationMapper.deleteByPrimaryKey(orgaId)==0)
            throw new BusinessException(500,"该数据不存在或已被删除!");
    }

    @Override
    public List<Map<String, Object>> SelectOrgTree(UserInfo user,Long orgaPid) {

        orgaPid = 0L;
        Map<String, Object> staffDto = staffMapper.selectStaffDetail(user.getUserid());
        orgaPid =(Long)staffDto.get("orgaId");
        if (staffDto==null) {
            throw new BusinessException(-1,"该人员未分配组织机构!");
        }
//        if (orgaPid==1) {
//            orgaPid = 0L;
//        }
        //如果传入为项目级,则查本身的组织架构
//        if ((Integer) staffDto.get("orgaLevel")==2){
//            List<Map<String, Object>> list = organizationMapper.selectOrgTree(null, (Long) staffDto.get("orgaId"));
//            if (list!=null){
//                Map<String, Object> projOrga = list.get(0);
//                projOrga.put("children",new ArrayList<>());
//                return Collections.singletonList(projOrga);
//            }
//        }
        List<Map<String, Object>> list = organizationMapper.selectOrgTree(null, orgaPid);
        list.forEach(map -> {
            map.put("children",getOrgTree((Long) map.get("orgaId")));
        });
        return list;
    }

    public List<Map<String, Object>> getOrgTree(Long orgaPid) {
        List<Map<String, Object>> list = organizationMapper.selectOrgTree(orgaPid,null);
        if (list.size() == 0)
            return null;

        list.forEach((orga) -> {
            orga.put("children", getOrgTree((Long) orga.get("orgaId")));
        });

        return list;
    }

    /**
     * 根据组织结构id查公司
     *
     * @param orgaId
     * @return
     */
    @Override
    public List<CompanyDto> GetCompanyByOrgaId(Long orgaId) {

        List<CompanyDto> dtos = companyMapper.selectByCompanyByOrgaId(orgaId);

        return dtos;
    }

    /**
     * 根据组织结构id查项目
     *
     * @param orgaId
     * @return
     */
    @Override
    public List<ProjectDto> GetProjByOrgaId(Long orgaId) {

        List<ProjectDto> dtos = projectMapper.selectByProjectByOrgaId(orgaId);

        return dtos;
    }

    /**
     * 在新增项目或其他时,新增组织架构
     *
     * @param orgaDto
     * @return
     */
    @Override
    public Long addOrga(OrganizationDto orgaDto) {
        orgaDto.setOrgaSort(3);
        orgaDto.setIsEnable(0);
        orgaDto.setOrgaLevel(2);
        orgaDto.setCreateTime(LocalDateTime.now());
        orgaDto.setUpdateTime(LocalDateTime.now());

        if (organizationMapper.insertSelective(orgaDto) == 0) {
            throw new BusinessException(500, "新增失败!");
        }
        Map<String, Object> orgaParent = organizationMapper.selectOrgDetail(orgaDto.getOrgaPid().longValue());
        orgaDto.setOrgaPathIds(StringUtils.toStringTrim(orgaParent.get("orgaPathId").toString().concat("-").concat(orgaDto.getOrgaId().toString())));
        orgaDto.setOrgaPathName(StringUtils.toStringTrim(orgaParent.get("orgaPathName").toString().concat("-").concat(orgaDto.getOrgaName().toString())));
        if (organizationMapper.updateByPrimaryKeySelective(orgaDto) == 0) {
            throw new BusinessException(500, "新增失败!");
        }
        return orgaDto.getOrgaId();
    }

    /**
     * 在修改项目或其他时,修改组织架构
     *
     * @param orgaDto
     */
    @Override
    public void updateOrga(OrganizationDto orgaDto) {
        orgaDto.setOrgaSort(3);
        orgaDto.setIsEnable(0);
        orgaDto.setOrgaLevel(2);
        orgaDto.setUpdateTime(LocalDateTime.now());

        if (organizationMapper.updateByPrimaryKeySelective(orgaDto) == 0) {
            throw new BusinessException(500, "修改失败!");
        }
        Map<String, Object> orgaParent = organizationMapper.selectOrgDetail(orgaDto.getOrgaPid().longValue());
        orgaDto.setOrgaPathIds(StringUtils.toStringTrim(orgaParent.get("orgaPathId").toString().concat("-").concat(orgaDto.getOrgaId().toString())));
        orgaDto.setOrgaPathName(StringUtils.toStringTrim(orgaParent.get("orgaPathName").toString().concat("-").concat(orgaDto.getOrgaName().toString())));
        if (organizationMapper.updateByPrimaryKeySelective(orgaDto) == 0) {
            throw new BusinessException(500, "修改失败!");
        }
    }
}
